<template>
  <div class="equipmentDataManagement zy-content ">
    <div class="search clear">
      <!--查询条件-->
      <searchPrams @search="changeNum" :type="1"/>
      <div class="list-layout mt16">
        <div class="btns clear">
          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button v-has="'scrapApplyAdd'" @click="addInfo">{{$t('common.NewScrap')}}</Button>
          <Button v-has="'scrapApplyExport'" @click="exportTemplateClick">{{$t('common.batchExport')}}</Button>
          <Button v-has="'scrapApplyDeleteByIds'" @click="handleMulDelete">{{$t('common.batchDelete')}}</Button>
          <Button @click="getTableColumns(columns)">{{ handleContextMenuStatus ? $t('显示操作栏'):$t('隐藏操作栏') }}</Button>
        </div>
        <div class="tableContent">
          <Table
              class="resizable-table" border @on-column-width-resize="onColumnWidthResize"
              ref="selection"
              row-key="id"
              :columns="columnsList"
              :data="dataSource"
              @on-selection-change="handleSelectionChange">

            <template slot-scope="{ row }" slot="statusStr">
              <span v-if="row.status === 1">{{ row.approvalResultStr }}</span>
              <span v-if="row.status !== 1">{{ row.statusStr }}</span>
            </template>

            <template slot-scope="{ row }" slot="action">
              <span v-has="'scrapApplyCheck'" class="operationBtn" @click="handleledgerDetail(row)">
                <i class="iconfont zy-common-chakan"></i>
                <span>{{ $t('common.Check') }}</span>
              </span>

              <template v-if="row.status === 1 && (row.approvalResult === 7 || row.approvalResult === 2)">
                 <span class="operationBtn"
                       v-has="'scrapApplyEditinfo'"
                       @click="updateInfo(row)">
                <i class="iconfont zy-common-bianji"></i>
                <span>{{ $t('common.Edit') }}</span>
              </span>
              </template>
          <template v-if="row.status === 1 && row.approvalResult === 1">
             <span class="operationBtn"
                   @click="withdraw(row)" v-has="'scrapApplyRollBack'">
                          <i class="iconfont zy-common-jieguo"></i>
                          <span>{{ $t('common.Withdraw') }}</span>
                        </span>
          </template>
          <template v-if="row.status === 1 && (row.approvalResult === 7 || row.approvalResult === 2)">
             <span class="operationBtn"
                   v-has="'scrapApplyDeleteByIds'"
                   @click="handleDelete(row)">
                      <i class="iconfont zy-common-shanchu"></i>
                      <span>{{ $t('common.Delete') }}</span>
                    </span>
          </template>
            </template>
          </Table>
        </div>
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="ids.length" />
          <Page :total="total"
                :page-size="pageSize"
                :page-size-opts="$variable.pageSizes"
                :current="pageNum"
                @on-change="changePageNum"
                @on-page-size-change="changePageSize"
                show-sizer show-total/>
        </div>
      </div>
    </div>
    <!--批量导入-->
    <import-excel-modal
        :isUpdate="isUpdate"
        :importExcelStateF="importExcelState"
        v-if="importExcelState"
        @importExcelChange="importExcelChange"
    />
    <!--新增报废-->
    <Modal :mask-closable="false"
        v-model="addStatus"
        :title="addtitle"
        :closable="false"
        class="modal-content-layout"
        width="900">
      <Row v-if="addStatus">
        <Col :span="24">
          <Form class="formListbox"
                :show-message="false"
                label-position="top"
          >
            <Col :span="24" class="title"><span>{{ $t('fault.DeviceInformation') }}</span></Col>
            <Col :span="24">
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                    <span>{{ $t('common.company') }}</span>
                  </template>
                  <Select v-model="formItemInfo.companyId"
                          filterable
                          clearable
                          :placeholder="`${$t('common.selectInfo')}`">
                    <Option v-for="(item,index) in tagList"
                            :label="item.name"
                            :value="item.id"
                            :key="index"/>
                  </Select>
                </FormItem>
              </Col>
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                     <span>{{ $t('common.Installation') }}</span>
                  </template>
                  <Cascader
                      :data="orgList"
                      change-on-select
                      :placeholder="`${$t('common.selectInfo')}`"
                      v-model="formItemInfo.equipPosition"
                      @on-change="formstaCasChange"
                  ></Cascader>
                </FormItem>
              </Col>
            </Col>
            <Col :span="24">
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                     <span style="color: red">*</span>
                     <span>{{ $t('设备流水号') }}</span>
                  </template>
                  <Select v-model="formItemInfo.deviceNo"
                          filterable
                          @on-change="deviceChange"
                          :remote-method="handleRemote"
                          clearable :placeholder="`${$t('common.selectInfo')}`">
                    <Option v-for="(item,index) in deviceNoList"
                            :value="item.deviceNo"
                            :disabled="item.disabled"
                            :key="index" :label="item.deviceLabel">
                    </Option>
                  </Select>
                </FormItem>
              </Col>
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                     <span>{{ $t('equipmentscrapped.From') }}</span>
                  </template>
                  <Select v-model="formItemInfo.sbly"
                          filterable
                          clearable :placeholder="`${$t('common.selectInfo')}`">
                    <Option v-for="item in sourceList"
                            :value="item.id"
                            :label="item.name"
                            :key="item.id"/>
                  </Select>
                </FormItem>
              </Col>
            </Col>
            <Col :span="24">
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                   <span>{{ $t('equipmentscrapped.UsedDept') }}</span>
                  </template>
                  <Input v-model="formItemInfo.useDept"
                         type="text" :placeholder="`${$t('common.inputInfo')}`"/>
                </FormItem>
              </Col>
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                   <span>{{ $t('equipmentscrapped.DepartmentalCostCenter') }}</span>
                  </template>
                  <Input type="text" v-model="formItemInfo.deptCostCenter"
                         :placeholder="`${$t('common.inputInfo')}`"
                         class="inputBorder"></Input>
                </FormItem>
              </Col>
            </Col>
            <Col :span="24" class="title"><span>{{ $t('preliminary.AssetInformation') }}</span></Col>
            <Col :span="24">
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                    <span>{{ $t('equipmentscrapped.AssetNo') }}</span>
                  </template>
                  <Input disabled v-model="formItemInfo.assetsNo"
                         type="text" :placeholder="`${$t('common.inputInfo')}`"/>
                </FormItem>
              </Col>
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                    <span>{{ $t('equipmentscrapped.OriginalValue') }}</span>
                  </template>
                  <Input disabled type="text" v-model="formItemInfo.assetsOriginal"
                         :placeholder="`${$t('common.inputInfo')}`"
                         class="inputBorder"></Input>
                </FormItem>
              </Col>
            </Col>
            <Col :span="24">
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                     <span>{{ $t('equipmentscrapped.ResidualValue') }}</span>
                  </template>
                  <Input disabled v-model="formItemInfo.assets"
                         type="text" :placeholder="`${$t('common.inputInfo')}`"/>
                </FormItem>
              </Col>
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                     <span>{{ $t('ledger.DepreciationLife') }}</span>
                  </template>
                  <Input disabled type="text" v-model="formItemInfo.depreciation"
                         :placeholder="`${$t('common.inputInfo')}`"
                         class="inputBorder"></Input>
                </FormItem>
              </Col>
            </Col>
            <Col :span="24">
              <Col :span="12" class="formListbox_Item">
                <FormItem>
                  <template #label>
                   <span>{{ $t('equipmentscrapped.UsedLife') }}</span>
                  </template>
                  <Input type="number" v-model.number="formItemInfo.useTime"
                         :placeholder="`${$t('common.inputInfo')}`"
                         class="inputBorder"></Input>
                </FormItem>
              </Col>
              <Col :span="12" class="formListbox_Item">
                <FormItem class="textlab">
                  <template #label>
                    <span style="color: red">*</span>
                    <span>{{ $t('equipmentscrapped.Scrap') }}</span>
                  </template>
                  <RadioGroup v-model="formItemInfo.normalScrap">
                    <Radio :label=1>{{$t('common.Yes')}}</Radio>
                    <Radio :label=0>{{$t('common.No')}}</Radio>
                  </RadioGroup>
                </FormItem>
              </Col>
            </Col>
            <Col :span="24">
              <Col :span="24" class="formListbox_Item">
                <FormItem>
                  <template #label>
                    <span style="color: red">*</span>
                    <span>{{ $t('spareParts.ScrapReason') }}</span>
                  </template>
                  <Input maxlength="200" type="textarea" v-model="formItemInfo.scrapReason"
                         :placeholder="`${$t('common.inputInfo')}`"
                         class="inputBorder"></Input>
                </FormItem>
              </Col>
            </Col>
            <Col :span="24">
              <Col :span="24" class="formListbox_Item">
                <FormItem>
                  <template #label>
                   <span>{{ $t('equipmentscrapped.Upload') }}</span>
                  </template>
                  <uploadFile style="float: left" ref="uploadFile" @change="uploadFileChange"/>
                  <div>
                  </div>
                </FormItem>
              </Col>
            </Col>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="fromCancle">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="fromAddOk">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false"
        v-model="delFaultCodeShowF"
        :title="$t('common.Delete')"
        class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{$t('common.sureDelete')}}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="delLoading" @click="deleteOk">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false"
        v-model="withdrawShow"
        :title="$t('common.Withdraw')"
        class="modal-title-layout">
<!--      <Row class="enableContent">-->
<!--        <Col span="24" class="enableContentInner">-->
<!--          <img width="95px" src="~images/event/del.png" alt="">-->
<!--        </Col>-->
<!--        <Col span="24" class="enableTips">-->
<!--          <span>{{$t('common.sureBack')}}？</span>-->
<!--        </Col>-->
<!--      </Row>-->
      <div class="icon red">
        <i class="iconfont zy-common-shibai1"></i>
      </div>
      <p class="title">
        <span>{{$t('common.sureBack')}}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="withdrawShow = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="withdrawLoading" @click="withdrawOk">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
  </div>
</template>
<!--////fileServer/upload-->
<script>
import { findOrgByToken } from '@/api/index.js';
import importExcelModal from '@/components/importExcel.vue';
import toggleTableOperation from "@/mixins/toggleTableOperation";
import recursion from '@/util/recursion';
import fileDownload from 'js-file-download';
import searchPrams from "./component/searchPrams";
import uploadFile from "./component/uploadFile";
// let timerNo = null
// let timerName = null
// let timerScrap = null
export default {
  name: "Scrapapplication",
  mixins:[toggleTableOperation],
  components: {
    importExcelModal,
    uploadFile,
    searchPrams
  },
  data() {
    return {
      deleteShowBtn:false,
      withdrawShow: false,
      withdrawLoading: false,
      record: {},
      file: [],
      sourceList: [
        {id: 1, name: '自制'},
        {id: 6, name: '内购'},
        {id: 2, name: '外购'},
        {id: 4, name: '租赁'},
        {id: 5, name: '客供'}
      ],
      scrapList: [
        {value: 0, name: '已提交'},
        {value: 1, name: '审批中'},
        {value: 2, name: '审批通过'},
        {value: 3, name: '审批不通过'},
        {value: 4, name: '已退回'},
        {value: 5, name: '已撤回'},
      ],
      deviceNoList: [],
      formItemInfo: {
        attachmentDTOS: []
      },
      addStatus: false,
      addtitle: '',
      isUpdate: false,//是否台账更新
      status: '',
      delId: '',
      delDeviceId: '',//台账删除
      uploadId: '',
      tagName: '',
      total: 0,
      pageNum: 1,
      pageSize: 10,
      delFaultCodeShowF: false,//删除模态框显示
      delDeviceLoading: false,
      uploadVisible: false,
      importExcelState: false,
      writeVisible: false,
      loading: false,
      uploadLoading: false,
      delLoading: false,
      delelteVisible: false,
      searchParams: {},
      checkBtnPermission: {},
      formItem: {
        deviceNo: ''
      },
      validateWritefunction: {
        deviceNo: [
          {required: true, message: '请输入机台号', trigger: 'blur'}
        ],
      },
      pageSizeOption: [10, 20, 30],
      statusList: [{id: 0, name: '全部'}, {id: 2, name: '已到位待安调'}, {id: 3, name: '安调中'}, {id: 4, name: '已安调待验收'}, {
        id: 5,
        name: '验收中'
      }, {id: 6, name: '已验收'}, {id: 7, name: '已入账'}],
      resultList: [{id: 0, name: '全部'}, {id: 1, name: '在用'}, {id: 2, name: '闲置'}, {id: 3, name: '报废'}],
      columns: [
        {
          type: 'selection',
          minWidth: 60,
          align: 'center'
        },
        {
        title: `${ this.$t('equipmentscrapped.ID') }`,
          key: 'deviceScrapApplyNo',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
          title: `${ this.$t('equipmentscrapped.ScrapStatus') }`,
          slot: 'statusStr',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
         title: `${ this.$t('equipCheck.EquipmentNo') }`,
          key: 'deviceNo',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
          title: `${ this.$t('equipCheck.EquipmentName') }`,
          key: 'deviceName',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
         title: `${ this.$t('common.company') }`,
          key: 'companyName',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
         title: `${ this.$t('common.Installation') }`,
          key: 'orgName',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
        title: `${ this.$t('equipmentscrapped.From') }`,
          key: 'sblyStr',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
         title: `${ this.$t('equipmentscrapped.AssetNo') }`,
          key: 'assetsNo',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
          title: `${ this.$t('equipmentscrapped.DepreciationLife') }`,
          key: 'depreciation',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
         title: `${ this.$t('equipmentscrapped.UsedLife') }`,
          key: 'useTime',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
          title: `${ this.$t('equipmentscrapped.OriginalValue') }`,
          key: 'assetsOriginal',
          align: 'center',
          minWidth: 260,
          resizable: true
        },
        {
          title: `${ this.$t('equipmentscrapped.ResidualValue') }`,
          key: 'assets',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
         title: `${ this.$t('equipmentscrapped.UsedDept') }`,
          key: 'useDept',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
          title: `${ this.$t('equipmentscrapped.DepartmentalCostCenter') }`,
          key: 'deptCostCenter',
          align: 'center',
          minWidth: 200,
          resizable: true
        },
        {
          title: `${ this.$t('equipmentscrapped.ApplyBy') }`,
          key: 'applyBy',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
          title: `${ this.$t('equipmentscrapped.ApplyTime') }`,
          key: 'applyDateTime',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          minWidth: 240,
          align: "center",
          fixed: 'right',
        }
      ],
      dataSource: [],
      tagList: [],
      orgList: [],
      fileList: [],
      showFileList: [],
      ids: [],
      deviceList: [
        {label: 'A类', value: 'A'},
        {label: 'B类', value: 'B'},
        {label: 'C类', value: 'C'},
      ],
      timerId: null,
      boxs: [{label: '是', value: '1'}, {label: '否', value: '2'}],
      userId: "",
      deviceNameList: [],
      deviceNoLists: [],
      deviceName: "",
      deviceNo: "",
      scrapNoList:[],
      scrapNo:"",
      queryDeviceNoName:""
    }
  },
  created() {
    this.getTableColumnsWidth(this.columns)
  },
  mounted() {
    // console.log(this.checkBtnPermission)
    this.userId = localStorage.getItem('ziyunFactoryUserId')
    this.getCompanyList()
    this.getOrgList()
    this.searchList()
    // this.getDeviceNo()
    // this.getDeviceName()
    // this.getScrap()
  },
  methods: {
    // scrapChange(val){
    //   this.searchParams.deviceScrapApplyNo = val
    // },
    // deviceNoChange(val){
    //   this.searchParams.deviceNo = val
    // },
    // deviceNameChange(val){
    //   const obj = this.deviceNameList.find(item => item.id === val)
    //   if (obj)
    //     this.searchParams.deviceName = obj.deviceName
    //   else
    //     this.searchParams.deviceName = ""
    // },
    // dateChange(arr) {
    //   if (!(Array.isArray(arr) && arr.length > 0)) {
    //     this.searchParams.startTime = arr[0]
    //     this.searchParams.endTime = arr[1]
    //   } else {
    //     delete this.searchParams.startTime
    //     delete this.searchParams.endTime
    //   }
    // },
    handleBeforeUpload() {

    },
    uploadFileChange(attachmentDTOS) {
      this.formItemInfo.attachmentDTOS = attachmentDTOS
    },
    filterData(arr, id) {
      let temp = [];
      let callback = function (nowArr, id) {
        for (let item of nowArr) {
          if (item.id === id) {
            temp.unshift(item.id);
            callback(arr, item.parentId)
            break;
          } else {
            if (item.children && item.children.length) {
              callback(item.children, id);
            }
          }
        }
      };
      callback(arr, id)
      return temp
    },
    deviceChange(val) {
      const obj = this.deviceNoList.find(item => item.deviceNo === val)
      if (obj) {
        const {assetsNo, id, assetsOriginal, depreciation, sbly, useDept,assets,useTime, costCenter, belongCompanyId, orgId} = obj;
        const arr = this.filterData(this.baseOrgList, orgId);

        this.formItemInfo = Object.assign(this.formItemInfo, {
          assetsNo,
          deviceId: id,
          assetsOriginal,
          depreciation,
          sbly,
          useDept,
          assets,
          equipPosition: [...arr],
          companyId: belongCompanyId,
          deptCostCenter: costCenter,
          deviceNo:val,
          useTime:(useTime/365).toFixed(2)
        })
      }else{
        this.formItemInfo = Object.assign(this.formItemInfo, {
          assetsNo:"",
          deviceId: "",
          assetsOriginal:"",
          depreciation:"",
          sbly:"",
          useDept:"",
          assets:"",
          deviceNo:"",
          useTime:""
        })
      }
    },
    // getScrap(val){
    //   clearTimeout(timerScrap)
    //   this.scrapNo = val;
    //   timerScrap = setTimeout(() => {
    //     this.axios({
    //       method: 'get',
    //       url: '/dms/scrapApply/getApplyNo',
    //       params: {
    //         applyNo: val,
    //       }
    //     }).then(res => {
    //       if (this.scrapNo === val) {
    //         this.scrapNoList = res.data;
    //       }
    //
    //     })
    //   }, 200)
    // },
    // getDeviceNo(val) {
    //   clearTimeout(timerNo)
    //   this.deviceNo = val;
    //   timerNo = setTimeout(() => {
    //     this.axios({
    //       method: 'get',
    //       url: '/dms/dmsDevice/deviceInfoByOrgId',
    //       params: {
    //         deviceName: val,
    //         orgId: ''
    //       }
    //     }).then(res => {
    //       if (this.deviceNo === val) {
    //         this.deviceNoLists = res.data;
    //       }
    //
    //     })
    //   }, 200)
    // },
    // getDeviceName(val) {
    //   this.deviceName = val;
    //   clearTimeout(timerName)
    //   timerName = setTimeout(() => {
    //     this.axios({
    //       method: 'get',
    //       url: '/dms/dmsDevice/deviceInfoByOrgId',
    //       params: {
    //         orgId: '',
    //         deviceName: val
    //       }
    //     }).then(res => {
    //       if (this.deviceName === val) {
    //         this.deviceNameList = res.data;
    //         this.$forceUpdate()
    //       }
    //     })
    //   })
    // },
    handleRemote(val) {
      this.queryDeviceNoName = val
      if (this.timerId) {
        clearTimeout(this.timerId)
      }
      if (val) {

        this.timerId = setTimeout(() => {
          /*if (!this.formItemInfo.orgId) {
            this.$Message.error('请选择安装位置!')
            return
          }*/
          this.axios({
            method: 'get',
            url: '/dms/dmsDevice/deviceInfoByOrgId',
            params: {
              orgId: this.formItemInfo.orgId,
              deviceNo: val
            }
          }).then(res => {
            if (this.queryDeviceNoName === val)
                this.deviceNoList = res.data.map(item=> {
                  item.deviceLabel = item.deviceMId + '-' + item.deviceNo + '-' + item.deviceName
                  if (item.deviceStatus == '3'){
                     item.disabled = true
                  }
                  return{
                    ...item,
                  }
                })
          })
        }, 200)
      }
    },
    getOrgList() {
      let params = {
        level: 3
      }
      findOrgByToken(params).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'id',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
          this.baseOrgList = res.data

        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },

    getOrgId(path, list) {
      const arr = path.split('/')
      let ids = [];
      let obj1 = {}
      let obj2 = {}
      let obj3 = {}
      obj1 = list.find(item => item.name = arr[0])

      if (obj1 && Array.isArray(obj1.children)) {
        obj2 = obj1.children.find(item => item.name = arr[1])
        ids.push(obj1.value)
      }
      if (obj2 && Array.isArray(obj2.children)) {
        obj3 = obj2.children.find(item => item.name = arr[2])
        ids.push(obj2.value)
      }

      if (obj3) {
        ids.push(obj3.value)
      }

      return ids
    },
    formstaCasChange(val) {
      this.formItemInfo.orgId = val[val.length - 1]

    },
    handleCasChange(val) {
      this.searchParams.orgId = val[val.length - 1]
    },
    //公司列表
    getCompanyList() {
      this.axios({
        method: 'get',
        url: '/basic/company/getCompanyListByUser',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          let arr = res.data.map(item => {
            return {
              ...item,
              id: item.id
            }
          })
          this.tagList = [...this.tagList, ...arr]
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    fromAddOk() {
      const params = this.formItemInfo
      const {
        attachmentDTOS,
        orgId,
        deviceNo,
        companyId,
        assetsNo,
        deviceId,
        assetsOriginal,
        depreciation,
        sbly,
        useDept,
        deptCostCenter,
        normalScrap,
        useTime,
        scrapReason,
        approvalId
      } = params;
      if (!companyId) {
        this.$Message.error('请选择公司！')
        return;
      }
      if (!orgId) {
        this.$Message.error('请选择安装位置！')
        return;
      }
      if (!deviceId) {
        this.$Message.error('请选择设备编号！')
        return;
      }
      if (!sbly) {
        this.$Message.error('请选择设备来源！')
        return;
      }
      if (!useDept) {
        this.$Message.error('请输入使用部门！')
        return;
      }
      if (!deptCostCenter) {
        this.$Message.error('请输入部门成本中心！')
        return;
      }

      if (!(normalScrap == 1 || normalScrap == 0)) {
        this.$Message.error('请选择是否是正常报废！')
        return;
      }
      if (!scrapReason) {
        this.$Message.error('请输入报废原因！')
        return;
      }
      let url = ''
      if (this.record.id) {
        params.id = this.record.id
        url = '/dms/scrapApply/update'
      } else {
        url = '/dms/scrapApply/add'
      }

      this.axios({
        method: 'post',
        url,
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success(!params.id ? '新增成功!' : '编辑成功')
          this.addStatus = false;
          this.formItemInfo = {}
          this.searchList()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    fromCancle() {
      this.formItemInfo = {}
      this.addStatus = false
    },
    addInfo() {
      this.addtitle = this.$t('common.NewScrap')
      this.file = []
      this.record = {}
      this.addStatus = true
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === 'success') {
        this.changeNum();
      }

    },
    handleChangeTab(name) {
      this.tagName = name
      this.searchParams = {}
      this.searchList()
    },
    exportTemplate() {
      const filName = '设备台账模板'
      this.axios({
        method: 'get',
        url: '/dms/dmsDeviceTz/template',
        responseType: 'blob',
        params: {}
      }).then(res => {
        // 
        fileDownload(res, filName + '.xlsx')
      })

    },
    exportTemplateClick() {

      let params = {};
      for (let key in this.searchParams) {
        if (key === 'orgId' && this.searchParams['orgId']) {
          const arr = this.searchParams[key]
          const {length, last = length - 1} = arr
          this.$set(params, key, arr[last])
        } else {
          if (this.searchParams[key]) {
            this.$set(params, key, this.searchParams[key])
          }
        }
      }
      if(this.ids.length > 0){
        params.ids = this.ids
      }

      const filName = '报废申请'
      this.axios({
        method: 'post',
        url: '/dms/scrapApply/export',
        responseType: 'blob',
        data: {
          ...params
        }
      }).then(res => {
        fileDownload(res, filName + '.xlsx')
      })

    },
    handleUpdateDeviceNo(row) {
      this.id = row.id
      this.formItem.deviceNo = row.deviceNo
      this.orgIdinfo = row.orgId
      this.writeVisible = true
    },
    handlePreview(item) {
      if (item.filePath) {
        window.open(this.util.filePathToUrl(item.filePath))
      }
    },
    delFileList(id) {
      this.delelteVisible = true
      this.delId = id
    },
    handleUpload(file) {
      this.uploadLoading = true
      // console.log(file)
      // let tmpList = []
      // this.fileList.push({
      //     fileName: file.name
      // })
      // console.log(this.fileList)
      // tmpList.push({
      //     fileName: file.name
      // })
      // this.showFileList = [...this.showFileList, ...tmpList]
      let formData = new FormData();
      formData.append("dir", 'device')
      formData.append("file", file);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.axios({
        method: 'post',
        url: '/fileServer/upload',
        data: formData,
        config,
      }).then(res => {
        // 
        if (res.code == 200) {
          let dmsAttachmentList = []
          dmsAttachmentList.push({
            deviceMId: this.uploadId,
            fileName: res.data.fileName,
            filePath: res.data.filepath,
            fileUrl: res.data.fileUrl
          })
          // let dmsAttachmentList = res.data.map(item => {
          //     return {
          //         deviceMId: this.uploadId,
          //         fileName: item.fileName,
          //         filePath: item.filepath,
          //         fileUrl: item.fileUrl
          //     }
          // })
          this.axios({
            method: 'post',
            url: '/dms/dmsDeviceTz/addFiles',
            data: dmsAttachmentList
          }).then(res => {
            // 
            if (res.code == 200) {
              this.getUploadFile()
              this.$Message.success('上传成功')
            } else {
              this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
            }
          }).finally(() => {
            this.uploadLoading = false
            // this.uploadVisible = false
          });
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
        }
      }).catch(() => {
        this.uploadLoading = false
      });
      return false;
    },
    handleManyFile(row) {
      this.uploadVisible = true
      this.uploadId = row.deviceMId
      // this.fileList = []
      this.getUploadFile()
    },
    getUploadFile() {
      this.axios({
        method: 'get',
        url: '/dms/dmsAttachment/get',
        params: {
          deviceMId: this.uploadId,
          type: 2
        }
      }).then(res => {
        // 
        if (res.code == 200) {
          this.fileList = res.data.map(item => {
            return {
              id: item.id,
              fileName: item.file_name,
              fileUrl: item.file_url
            }
          })
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
        }
      }).finally(() => {

      });
    },
    handleOk() {
      this.loading = true
      this.axios({
        method: 'post',
        url: '/dms/dmsDeviceTz/updateDeviceNo',
        data: {
          id: this.id,
          orgId: this.orgIdinfo,
          deviceNo: this.formItem.deviceNo
        }
      }).then(res => {
        // 
        if (res.code === 200) {
          this.$Message.success(({content: '修改成功', duration: 3, closable: true}));
          this.searchList()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.loading = false
        this.writeVisible = false
      })

    },
    //批量导入
    handleBatchImport(status) {
      this.isUpdate = status == 1 ? true : false
      this.importExcelState = true;

    },
    //批量打印
    handleBatchPrint() {
      this.$refs.ledgerBatchPrintModal.show(this.ids)
    },
    handleChangeVisible() {
      this.$refs.selection.selectAll(false);
    },
    //批量操作
    handleSelectionChange(selectionData) {
     let status = false;
      let arr = [];
      selectionData.forEach(item => {
        arr.push(item.id)
      })
      this.ids = arr

      const obj = selectionData.find(item=> item.createBy/1 === this.userId/1 && item.status/1===3)
      if (obj){
        this.deleteShowBtn = true
      }else{
        this.deleteShowBtn = false
      }
    },
    //分页
    changeNum(params) {
      this.pageNum = 1;
      this.searchList(params);
    },
    // search(params){
    //   this.pageNum = 1;
    //   this.searchList(params);
    // },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList(_params) {
      let params = {
        companyId: this.tagName ? this.tagName : '',
        pageNo: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in _params) {
        if (key === 'orgId' && _params['orgId']) {
          const arr = _params[key]
          const {length, last = length - 1} = arr
          this.$set(params, key, arr[last])
        } else {
          if (_params[key]) {
            this.$set(params, key, _params[key])
          }
        }
      }


      this.axios({
        method: 'post',
        url: '/dms/scrapApply/applyList',
        data: params
      }).then(res => {
        // 
        if (res.code === 200) {
          this.dataSource = (res.data || {}).list || []
          res.data.list.forEach(val => {
            if (val.categoryName) {
              val.categoryName = val.categoryName + '类'
            }
          })
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    //设备类别
    getDeviceList() {
      this.axios({
        method: 'get',
        url: '/dms/dmsCategory/getSelectList',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          // res.data.forEach(val=>{
          //   switch (val['label']) {
          //     case 'MME':
          //       val.label = 'A类'
          //           break;
          //     case 'HME':
          //       val.label = 'B类'
          //       break;
          //     case 'AME':
          //       val.label = 'C类'
          //       break;
          //   }
          // })
          this.deviceList = res.data
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleledgerScore({deviceMId, assetsNo, id}) {
      this.$router.push({
        path: '/devBasic/equipmentsLedgerManagement/equipmentScore',
        query: {
          deviceMId,
          assetsNo,
          id,
          status: 'score'
        }
      })
    },
    //详情页
    handleledgerDetail({deviceMId, assetsNo, id}) {
      this.$router.push({
        path: '/devBasic/equipmentscrapped/scrapapplicationDetail',
        query: {
          id,
        }
      })
    },
    handlePrint(record) {
      this.$refs.ledgerPrintModal.show(record)
    },
    withdraw(record) {
      this.record = record
      this.withdrawShow = true
    },
    withdrawOk() {
      this.withdrawLoading = true
      this.axios({
        method: 'get',
        url: '/dms/scrapApply/rollBack',
        params: {
          applyId: this.record.id
        }
      }).then(res => {
        // 
        if (res.code === 200) {
          this.searchList()
          this.$Message.success(({content: '撤回成功！', duration: 2, closable: true}));
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.withdrawShow = false
        this.withdrawLoading = false
      })
    },
    //删除
    handleDelete(record) {
      this.status = 0
      this.delDeviceId = record.id
      this.delFaultCodeShowF = true
    },
    //批量删除
    handleMulDelete() {
      if(this.ids.length < 1){
        this.$Message.error(({content: '至少选择一条数据！', duration: 2, closable: true}));
        return;
      }
      this.status = 1
      this.delFaultCodeShowF = true
    },
    deleteOk() {
      this.delLoading = true
      if (this.status == 0) {
        this.axios({
          method: 'post',
          url: '/dms/scrapApply/deleteByIds',
          data: [this.delDeviceId]
        }).then(res => {
          // 
          if (res.code === 200) {
            this.searchList()
            this.$Message.success(({content: '删除成功！', duration: 2, closable: true}));
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        }).finally(() => {
          this.delLoading = false
          this.delFaultCodeShowF = false
        })
      } else {
        this.axios({
          method: 'post',
          url: '/dms/scrapApply/deleteByIds',
          data: this.ids
        }).then(res => {
          // 
          if (res.code === 200) {
            this.searchList()
            this.$Message.success(({content: '批量删除成功！', duration: 2, closable: true}));
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        }).finally(() => {
          this.delLoading = false
          this.delFaultCodeShowF = false
        })
      }

    },
    updateInfo(record) {
      this.addtitle = this.$t('common.editScrap')
      this.file = []
      this.record = record
      this.axios({
        method: 'get',
        url: '/dms/scrapApply/info',
        params: {id: record.id}
      }).then(res => {
        if (res.code === 200) {
          this.addStatus = true
          let {
            assets,
            assetsNo,
            assetsOriginal,
            depreciation,
            deptCostCenter,
            companyId,
            orgId,
            deviceNo,
            deviceId,
            useDept,
            sbly,
            useTime,
            normalScrap,
            scrapReason,
            id,
            position6,
            attachmentVOS,
            deviceName,
          } = res.data;
          if (!Array.isArray(attachmentVOS)) attachmentVOS = [];
          this.formItemInfo = Object.assign({
            assets,
            assetsNo,
            assetsOriginal,
            depreciation,
            deptCostCenter,
            deviceName,
            companyId,
            orgId,
            deviceNo,
            deviceId,
            useDept,
            sbly: Number(sbly),
            useTime,
            normalScrap,
            scrapReason,
            id,
            onlyOrgId: orgId,
            equipPosition: this.getOrgId(position6, this.orgList),
            attachmentDTOS: attachmentVOS,
            approvalId: record.approvalId
          })



          this.$nextTick(() => {
            this.$refs.uploadFile.setFiles(attachmentVOS)
          })

          this.handleRemote(deviceNo)

        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
  }

}
</script>

<style scoped lang="scss">
::v-deep .ivu-select-item-disabled{
  text-decoration:line-through;
}
.formListbox {
  .formListbox_Item {
    padding: 0 5px;
  }

  .title {
    span {
      display: block;
      font-size: 18px;
      font-weight: bold;
    }

    margin-bottom: 15px;
  }
}

::v-deep .ivu-upload-drag {
  border: none !important;
  text-align: left;
}

.equipmentDataManagement {
  .ivu-tabs.ivu-tabs-card {
    .ivu-tabs-tab {
      width: 120px !important;
      text-align: center;
    }

    ::v-deep .ivu-tabs-tab.ivu-tabs-tab-active {
      color: #ffffff;
      background-color: #2d8cf0;
    }
  }
}

.file-list {
  /*margin: 20px;*/
  .item-src {
    width: 80%;
    display: inline-block;
    line-height: 26px;
    color: #187bdb;
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .item-icon {
    width: 20%;
    display: inline-block;
    margin-top: 4px;
  }
}

</style>
